package grpc

import (
  "context"
  "gitlab.local/backend/proto/dto"
  "manager/bll"
  "manager/client/broker"
  "manager/model"
)

type Controls struct {
}

func (e *Controls) UpdateControl(ctx context.Context, in *dto.ControlInfoRequest, out *dto.ControlInfo) error {

  var err error
  bikeInfo, _ := bll.CacheBike.GetBikeInfoBySn(in.SnCode)
  if bikeInfo != nil {

    if resp, e1 := bll.Control.Find(ctx, &model.ControlInfoRequest{
      Id: bikeInfo.ControlId,
    }); e1 != nil {
      return e1
    } else {
      // 构造回包
      *out = dto.ControlInfo{
        Id:              resp.Id,
        FrameCode:       resp.FrameCode,
        FirmwareId:      resp.FirmwareId,
        FirmwareVersion: resp.FirmwareVersion,
        SnCode:          resp.SnCode,
        Mac:             resp.Mac,
        Imei:            resp.Imei,
        Iccid:           resp.Iccid,
        Imsi:            resp.Imsi,
        CreatedAt:       resp.CreatedAt,
        UpdatedAt:       resp.UpdatedAt,
      }
    }

    // 更新设备中控版本
    err = bll.Control.Update(context.Background(), &model.ControlUpdateRequest{
      Id:              bikeInfo.ControlId,
      FirmwareVersion: &in.FirmwareVersion,
    })
  }

  if err != nil {
    return err
  }

  // 同步设备信息到设备影子
  return broker.Consumer.SyncDeviceInfoToShadow(in.SnCode, dto.EnUpdateType_ATTRIBUTE, map[string]interface{}{
    "firmware_version": in.FirmwareVersion,
  })
}

func (e *Controls) GetControl(ctx context.Context, in *dto.ControlInfoRequest, out *dto.ControlInfo) error {

  bikeInfo, _ := bll.CacheBike.GetBikeInfoBySn(in.SnCode)
  resp, err := bll.Control.Find(context.Background(), &model.ControlInfoRequest{
    Id: bikeInfo.ControlId,
  })

  if err != nil {
    return err
  }

  // 构造回包
  *out = dto.ControlInfo{
    Id:              resp.Id,
    FrameCode:       resp.FrameCode,
    FirmwareId:      resp.FirmwareId,
    FirmwareVersion: resp.FirmwareVersion,
    SnCode:          resp.SnCode,
    Mac:             resp.Mac,
    Imei:            resp.Imei,
    Iccid:           resp.Iccid,
    Imsi:            resp.Imsi,
    CreatedAt:       resp.CreatedAt,
    UpdatedAt:       resp.UpdatedAt,
  }

  return err
}
